package com.lnw.travels.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lnw.travels.entity.Result;
import com.lnw.travels.entity.TUser;
import com.lnw.travels.service.UserService;
import com.lnw.travels.utils.CreateImageCode;
import com.lnw.travels.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
@CrossOrigin//允许跨域
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 检查token是否有效
     * @param request
     * @return
     */
    @GetMapping("checkToken")
    public Result checkToken(HttpServletRequest request){
        String token = request.getHeader("token");
        System.out.println(token);
        Result result = new Result();
        try {
            if (JwtUtils.checkToken(token)){
                result.setStatus(true);
            }else{
                result.setStatus(false).setMsg("请登录后访问！");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setStatus(false).setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 生成验证码
     *
     * @param
     * @param request
     * @throws IOException
     */
    @GetMapping("getImage")
    public Map<String,String> getImage(HttpServletRequest request) throws IOException {
        Map<String,String> result = new HashMap<>();
        CreateImageCode imageCode = new CreateImageCode();
        //获取验证码
        String securityCode = imageCode.getCode();
        //验证码存入session
        String key = new SimpleDateFormat("yyyyMMddHH:mm:ss").format(new Date());
        request.getServletContext().setAttribute(key,securityCode);
        //session.setAttribute("code", securityCode);
        //生成图片
        BufferedImage image = imageCode.getBuffImg();
        //进行base64编码
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", bos);
        String string = Base64Utils.encodeToString(bos.toByteArray());
        result.put("key",key);
        result.put("image",string);
        return result;
    }

    /**
     * 用户注册
     * @param code
     * @param key
     * @param user
     * @param request
     * @return
     */
    @PostMapping("register")
    public Result Register(String code, String key, @RequestBody TUser user, HttpServletRequest request){
        Result result = new Result();
        try{
            //获取验证码
            String keyCode = (String) request.getServletContext().getAttribute(key);
            //判断用户名是否存在
            QueryWrapper<TUser> wrapper = new QueryWrapper<>();
            wrapper.eq("username",user.getUsername());
            TUser oneUser = userService.getOne(wrapper);
            if (oneUser==null){
                //存在该用户可以继续注册
                if (keyCode.equalsIgnoreCase(code)){
                    //注册用户
                    userService.save(user);
                    result.setMsg("注册成功");

                }else{
                    throw new RuntimeException("验证码错误！");
                }
            }else{
                //存在该用户
                throw new RuntimeException("该用户已存在！");
            }

        }catch (Exception e){
            e.printStackTrace();
            result.setStatus(false).setMsg(e.getMessage());
        }

        return  result;
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @PostMapping("login")
    public Result login(@RequestBody TUser user,HttpServletRequest request){
        Result result = new Result();
        try{
            QueryWrapper<TUser> wrapper = new QueryWrapper<>();
            wrapper.eq("username",user.getUsername());
            TUser one = userService.getOne(wrapper);
            if (one!=null){
                if (user.getPassword().equals(one.getPassword())){
                    request.getServletContext().setAttribute("loginInfo",user);
                    user.setToken(JwtUtils.createToken());
                    //登录成功
                    result.setMsg("登录成功").setData(user);
                }else{
                    result.setStatus(false).setMsg("密码错误");
                }
            }else{
                result.setStatus(false).setMsg("此用户不存在");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setStatus(false).setMsg("登录失败");
        }
        return result;
    }

}
